package org.springboot.demo.controller;

import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.springboot.demo.domain.Borrow;
import org.springboot.demo.framework.solr.CitySolrRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Iterator;

/**
 * Solr调用实例
 * Created by Robin on 2017/6/22.
 */
@RestController
public class SolrController {

    @Autowired
    private CloudSolrServer solrServer;

    @RequestMapping("/solr")
    public ModelAndView testSolr() throws IOException, SolrServerException {
        /*Iterator<Borrow> it= cityRepository.findByProName("dc还本付息-提前还款2").iterator();
        StringBuffer sb = new StringBuffer();
        while(it.hasNext()){
            System.out.println("=======solr======="+it.next().toString());
            sb.append(String.valueOf(it.next()));
        }*/

        ModifiableSolrParams params = new ModifiableSolrParams();
        params.add("q","proId:11137520");
        params.add("ws","json");
        params.add("start","0");
        params.add("rows","10");
        QueryResponse response = null;
        StringBuffer sb = new StringBuffer();
        try{
            response= solrServer.query(params);
            SolrDocumentList results = response.getResults();

            for (SolrDocument document : results) {
                sb.append("\n id:").append(document.getFieldValue("id")).append("\nproName:").append(document.getFieldValue("proName"));
            }
        }catch(Exception e){
            e.getStackTrace();
        }
        System.out.println(response.toString());
        ModelAndView model = new ModelAndView();
        model.addObject("msg", sb.toString());
        model.setViewName("index");
        return model;
    }
}
